import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { RootState } from "@/shared/typicode";
import { heroesState } from "@/shared/typicode/models";
import {
  getHeroByIdParams,
  getHeroInfoById,
  getHeroesList,
  getHeroesListParams,
  getInfoByUrl,
} from "@/shared/typicode/heroes";

// const heroesCreateSlice = buildCreateSlice({
//   creators: { asyncThunk: asyncThunkCreator },
// });
export const getPeople = createAsyncThunk("heroes/getPeople", async (params?: getHeroesListParams) => {
  const { data } = await getHeroesList(params);
  return data;
});

export const getPeopleInfoById = createAsyncThunk("heroes/getPeopleInfoById", async (params: getHeroByIdParams) => {
  const { data } = await getHeroInfoById(params);
  return data;
});

export const getInfoByUrlThunk = (url: string | string[]) => {
  if (!url) {
    return [];
  }
  if (typeof url === "string") {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const res: string[] = [];
    Promise.all([getInfoByUrl(url)]).then(responses =>
      responses.forEach(({ data }) => res.push(data?.name || data?.title))
    );
    return res;
  }
  const res: string[] = [];
  Promise.all(url.map(url => getInfoByUrl(url))).then(responses =>
    responses.forEach(({ data }) => res.push(data?.name || data?.title))
  );
  return res;
};

/**
 * Начальная состояние Redux slice для героев
 */
const initialState: heroesState = {
  heroesList: [],
  heroInfo: null,
  nextPageUrl: "",
  isLoading: false,
  error: false,
  history: [],
};

/**
 * Создание Redux slice для героев
 */
const heroesSlice = createSlice({
  name: "heroes",
  initialState,
  reducers: {
    addHistory: (state, action) => {
      state.history = [...state.history, action.payload];
    },
    removeHeroInfo: state => {
      state.heroInfo = null;
    },
  },
  extraReducers: builder => {
    builder.addCase(getPeople.pending, state => {
      state.isLoading = true;
    });
    builder.addCase(getPeople.rejected, state => {
      state.isLoading = false;
    });
    builder.addCase(getPeople.fulfilled, (state, action) => {
      state.isLoading = false;
      state.heroesList = action.payload.results;
    });
    builder.addCase(getPeopleInfoById.pending, state => {
      state.isLoading = true;
      state.error = false;
    });
    builder.addCase(getPeopleInfoById.rejected, state => {
      state.isLoading = false;
      state.error = true;
    });
    builder.addCase(getPeopleInfoById.fulfilled, (state, action) => {
      state.isLoading = false;
      state.heroInfo = action.payload;
      state.error = false;
    });
  },
});

// * @selectors
/**
 * Получение store
 */
const heroesSelector = (state: RootState) => state.heroes;
/**
 * Получение массива героев
 */
export const selectHeroesList = (state: RootState) => heroesSelector(state).heroesList;
/**
 * Получение полной информации о герое
 */
export const selectHeroInfo = (state: RootState) => heroesSelector(state).heroInfo;

export const selectIsLoading = (state: RootState) => heroesSelector(state).isLoading;

export const selectError = (state: RootState) => heroesSelector(state).error;

export const selectHistory = (state: RootState) => heroesSelector(state).history;
/**
 * Получение ссылки на следующую страницу
 */
export const selectNextPageUrl = (state: RootState) => heroesSelector(state).nextPageUrl;

// * @actions
/**
 * Экшены героев
 */
export const heroesActions = heroesSlice.actions;

export default heroesSlice.reducer;
